import { apiService } from "@service/index";
import { saveGuestChannels } from "@slice/guestChannel";

const channelEndpoints = apiService
  .enhanceEndpoints({ addTagTypes: ["userChannels"] })
  .injectEndpoints({
    endpoints: (build) => ({
      // 获取登录用户的频道列表
      requestUserChannels: build.query<ChannelResponse, undefined>({
        query: () => ({ url: "/user/channels" }),
        providesTags: ["userChannels"],
      }),
      // 获取访客频道列表
      requestGuestChannels: build.query<ChannelResponse, undefined>({
        query: () => ({ url: "/user/channels" }),
        async onQueryStarted(arg, api) {
          // 等待请求完成
          const response = await api.queryFulfilled;
          // 将访客频道列表保存到状态切片中
          api.dispatch(saveGuestChannels(response.data.data.channels));
        },
      }),
      // 删除用户频道
      deleteUserChannel: build.mutation<null, string>({
        query: (id) => ({ url: `/user/channels/${id}`, method: "DELETE" }),
        invalidatesTags: ["userChannels"],
      }),
      // 获取所有频道
      requestAllChannels: build.query<ChannelResponse, undefined>({
        query: () => ({ url: "/channels" }),
      }),
      // 添加用户频道
      addUserChannel: build.mutation<
        AddChannelResponse,
        { channels: ChannelState[] }
      >({
        query: (body) => ({ url: "/user/channels", method: "PATCH", body }),
        invalidatesTags: ["userChannels"],
      }),
    }),
  });

export const {
  useRequestUserChannelsQuery,
  useLazyRequestGuestChannelsQuery,
  useDeleteUserChannelMutation,
  useRequestAllChannelsQuery,
  useAddUserChannelMutation,
} = channelEndpoints;
